package com.aries.dubbo.like.rpc.client.util;

import com.aries.dubbo.like.rpc.client.channel.cache.AddressChannelMap;
import com.aries.dubbo.like.rpc.service.util.discover.zk.ZookeeperDiscovery;
import com.aries.dubbo.like.rpc.service.util.discover.zk.ZookeeperRegistry;
import io.netty.channel.Channel;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Author: aries
 * Date: 2018/8/23
 * Description: 服务发现工具类
 */
public class ServiceDiscoveryUtil {

    public static Channel getServiceChannel(Class clz) {
        String host = getHost(clz);

        if (host == null) {
            throw new RuntimeException("rpc consumer:" + clz.getName() + "  has no provider");
        }

        Channel channel = AddressChannelMap.get(host);
        //如果连接不可用，重试一次
        if (channel == null || !channel.isWritable()) {
            ZookeeperRegistry.updateZkData(host);
            host = getHost(clz);

            if (host == null) {
                throw new RuntimeException("rpc consumer:" + clz.getName() + "  has no provider");
            }

            channel = AddressChannelMap.get(host);
            if (channel == null || !channel.isWritable()) {
                ZookeeperRegistry.updateZkData(host);
            }
        }
        return channel;
    }

    private static String getHost(Class<?> clz) {
        //此处应做负载均衡。
        List<String> hosts = ZookeeperDiscovery.getRegistryData().get(clz.getName());
        if (hosts == null) {
            throw new RuntimeException("rpc consumer:" + clz.getName() + "  has no provider");
        }
        return hosts.get(0);
    }
}
